<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>行程管理</el-breadcrumb-item>
      <el-breadcrumb-item>行程列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getTripList">
            <el-button slot="append" icon="el-icon-search" @click="getTripList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="getUserList" :disabled = addDisabled>添加行程</el-button>
        </el-col>
      </el-row>

      <!-- 订单列表 -->
      <el-table :data="tripList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>

        <el-table-column label="行程价格" prop="tripPrice" ></el-table-column>
        <el-table-column label="碳积分"   prop="tripCarbonPoint" ></el-table-column>
        <el-table-column label="付款状态">
          <template slot-scope="scope">
            <el-tag type="success" size="mini" v-if="scope.row.tripStatus">已付款</el-tag>
            <el-tag type="danger" size="mini" v-else>未付款</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入站点" prop="tripInStationName"></el-table-column>
        <el-table-column label="入站时间" prop="tripInTime"></el-table-column>
        <el-table-column label="出站点" prop="tripOutStationName"></el-table-column>
        <el-table-column label="出站时间" prop="tripOutTime"></el-table-column>
        <el-table-column label="用户" prop="user.username"></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!--显示用户信息-->
            <el-button type="warning" icon="el-icon-view" size="mini" @click="showUser(scope.row)"></el-button>
<!--            &lt;!&ndash; 修改按钮 &ndash;&gt;-->
<!--            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)" :disabled = editDisabled></el-button>-->
<!--            &lt;!&ndash; 删除按钮 &ndash;&gt;-->
<!--            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row)" :disabled=deleteDisabled></el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加行程" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm"  ref="addFormRef" label-width="70px"><!--:rules="addFormRules"-->
        <el-form-item label="起始时间" prop="time">
          <div class="block">
<!--            <span class="demonstration"></span>-->
            <el-date-picker
              v-model="addForm.value1"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="addForm.price"></el-input>
        </el-form-item>
        <el-form-item label="碳积分" prop="point">
          <el-input v-model="addForm.carbonPoint"></el-input>
        </el-form-item>
        <el-form-item label="付款状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择">
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户" prop="status">
          <el-select v-model="addForm.user" placeholder="请选择">
            <el-option
              v-for="item in userlist"
              :key="item.userId"
              :label="item.username"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="进站点" prop="inStation">
          <el-cascader
            v-model="addForm.address1"
            :options="cityData"
            :props="{ expandTrigger: 'hover' }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="出站点" prop="outStation">
          <el-cascader
            v-model="addForm.address2"
            :options="cityData"
            :props="{ expandTrigger: 'hover' }"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTrip">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
  import cityData from './straion.js'
  import Bus from '../../util/bus.js'
  export default {

    data () {
      return {

        cityData,
        userlist: [],
        status:[{
          value: true,
          label: '已付款'
        }, {
          value: false,
          label: '未付款'
        }],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },

        // 订单列表查询参数
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 5
        },
        userQuery:{
          query: '',
          pagenum: 1,
          pagesize: 100000,
        },
        total: 0,
        // 订单列表
        tripList: [],
        addDialogVisible: false,
        //增删改按钮是否可用
        addDisabled:false,
        deleteDisabled:false,
        editDisabled:false,
        // 添加行程的表单数据
        addForm: {
          user:"",
          status:false,
          price:'0',
          carbonPoint:'0',
          value1: [new Date(2021, 1, 0 , 0, 0), new Date(2021, 1, 0, 0, 0)],
          address1: '',
          address2: ''
        },

      }
    },
    created () {

      this.getTripList()
      if(window.sessionStorage.getItem('userId')!='')
        this.getTripListById(window.sessionStorage.getItem('userId'))
      window.sessionStorage.setItem('userId', '')
    },
    methods: {
      async getUserList(info){
        this.addDialogVisible = true
        const { data: res } = await this.$http.get('users', {
          params: this.userQuery
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取用户列表失败！')
        }
        //this.$message.success('获取用户列表成功！'+info)
        this.userlist = res.data.users
      },
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
        this.addForm.address1='';
        this.addForm.address2='';
      },
      async getTripListById(id) {
        const {data: res} = await this.$http.get(`trips/${id}`, {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取行程列表失败！')
        }
        console.log(res)
        this.total = res.data.total
        this.tripList = res.data.trips
      },
      async getTripList() {
        const {data: res} = await this.$http.get('trips', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取行程列表失败！')
        }
        console.log(window.sessionStorage.getItem('userId'))
        this.total = res.data.total
        this.tripList = res.data.trips
      },
      // 点击按钮，添加新行程
      addTrip() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          // 可以发起添加用户的网络请求

          const { data: res } = await this.$http.post('trips', this.addForm)
          console.log(res.meta.status)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.errMsg)
          }

          this.$message.success('添加行程成功！')
          // 隐藏添加用户的对话框
          this.addDialogVisible = false
          // 重新获取用户列表数据
          this.getTripList()
        })
      },
      //根据id删除行程信息
      removeUserById(){

      },
      // 分页
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getTripList()
      },
      handleCurrentChange(newSize) {
        this.queryInfo.pagenum = newSize
        this.getTripList()
      },
      showUser(TripInfo){
        console.log(TripInfo)

        window.sessionStorage.setItem('activePath', "/Users")
        this.$router.push('/Users')
        Bus.$emit('changetoUser')
        window.sessionStorage.setItem('username', TripInfo.user.username)
      },
      showEditDialog() {
        this.addDialogVisible = true
      },
      addressDialogClosed() {
        this.$refs.addFormRef.resetFields()
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-cascader {
    width: 100%;
  }
</style>
